<template>
  <div class="detail">
    <SearchIcon :title="'网易严选'"></SearchIcon>
    <div class="header">
      <!-- 轮播图 -->
      <van-swipe class="headerSwiper" :show-indicators="false" :autoplay="3000" :loop="false">
        <van-swipe-item v-for="(banner, index) in skuImageList" :key="banner.id" class="swiperItem">
          <img class="itemImg" :src="banner.imgUrl" alt="" />
        </van-swipe-item>
      </van-swipe>
    </div>
    <div class="detailPrice">
      <div class="priceLeft">
        <div class="leftTop">特价：{{ price }}</div>
        <div class="leftBottom">
          <div class="bottomY">
            <span class="Bottomprice"><span style="font-size: 18px">￥:</span>{{ price }}</span
            ><span class="priceToHand"><span class="hand">到手￥</span>{{ price }}</span>
          </div>
        </div>
      </div>
      <div class="priceRight">
        <img class="rightImg" src="https://yanxuan.nosdn.127.net/static-union/16700365748af178.png" alt="" />
      </div>
    </div>
    <div class="baseInfo">
      <div class="infoMain">
        <div class="mainLeft">
          <div class="name">{{ skuInfo?.skuName }}</div>
          <div class="brandInfo">
            <div class="brand">
              <div class="proLogo"></div>
              <img class="brandLogo" src="https://yanxuan-item.nosdn.127.net/953fd27555b9382e9d3d656a54398953.png" alt="" />
              <span class="title">网易严选</span>
            </div>
          </div>
          <div class="desc">推荐理由</div>
        </div>
        <div class="mainRight">
          <div class="rate">
            <div class="percentage">99.5%</div>
            <div class="applauseRate">好评率</div>
          </div>
          <div class="rightClick">></div>
        </div>
      </div>
      <div class="recmBanner">
        <div class="angleTop">
          <span class="angleContent"></span>
        </div>
        <ul class="ulli">
          <li class="lili">
            <div class="key">1</div>
            <div class="recommendReason">{{ skuInfo?.skuDesc }}</div>
          </li>
          <li class="lili">
            <div class="key">2</div>
            <div class="recommendReason">{{ skuInfo?.skuDesc }}</div>
          </li>
          <li class="lili">
            <div class="key">3</div>
            <div class="recommendReason">{{ skuInfo?.skuDesc }}</div>
          </li>
        </ul>
      </div>
    </div>
    <div class="welfareCard">
      <img class="cardImg" src="https://yanxuan.nosdn.127.net/static-union/166918388792a1cd.png?imageView&quality=75" alt="" />
    </div>
    <div class="proupInfo">
      <div style="height: 50px" class="proupP">
        <van-cell style="height: 50px; line-height: 50px" is-link @click="handleClick(1)" title="邮费：满99包邮"></van-cell>
        <van-popup
          :overlay-style="{ backgroundColor: ' rgba(0,0,0,.4)' }"
          v-model:show="showProup1"
          closeable
          position="bottom"
          :style="{ height: '55%' }"
        >
          <van-nav-bar title="邮费" />
          <div class="nav">
            <div class="picker-z">
              <div class="ruleTitle">满99元免邮</div>
              <div class="ruleContent">
                本商品由严选自营仓发货，单笔订单金额（不含邮费）大陆地区满99元免邮费，不满99元收取8元邮费；港澳台地区满500元免邮费，不满500元收取30元邮费；海外地区以下单页提示运费为准。
              </div>
            </div>
          </div>
        </van-popup>
      </div>
      <div style="height: 50px" class="proupP">
        <van-cell style="height: 50px; line-height: 50px" is-link @click="handleClick(2)" title="促销：满299领取赠品"></van-cell>
        <van-popup
          :overlay-style="{ backgroundColor: ' rgba(0,0,0,.4)' }"
          v-model:show="showProup2"
          closeable
          position="bottom"
          :style="{ height: '55%' }"
        >
          <van-nav-bar title="邮费" />
          <div class="nav">
            <div class="picker-z">
              <div class="ruleTitle">满99元免邮</div>
              <div class="ruleContent">
                本商品由严选自营仓发货，单笔订单金额（不含邮费）大陆地区满99元免邮费，不满99元收取8元邮费；港澳台地区满500元免邮费，不满500元收取30元邮费；海外地区以下单页提示运费为准。
              </div>
            </div>
          </div>
        </van-popup>
      </div>

      <div style="height: 50px" class="proupP">
        <van-cell style="height: 50px; line-height: 50px" is-link @click="handleClick(3)" title="购物返：最高18积分"></van-cell>
        <van-popup
          :overlay-style="{ backgroundColor: ' rgba(0,0,0,.4)' }"
          v-model:show="showProup3"
          closeable
          position="bottom"
          :style="{ height: '55%' }"
        >
          <van-nav-bar title="什么是购物返" />
          <div class="nav">
            <div class="picker-z">
              <div class="ruleTitle">关于购物返回馈金：</div>
              <div class="ruleContent">
                <ul>
                  <li>1. 用户在严选主站购物，确认收货后按商品售价的10%返购物积分</li>
                  <li>2. 购物返积分数值精确到个位（小数点后全部舍弃，不进行四舍五入）</li>
                  <li>3. 拼团/众筹/砍价/虚拟商品和礼品卡支付商品订单不支持返积分</li>
                  <li>4. 购买礼品卡订单不返积分，礼品卡消费时，按照实际消费额度进行积分返赠</li>
                  <li>5. 如商品订单完成后退货，则在退货流程发起后24小时内对该笔订单发放的积分数进行扣除</li>
                  <li>6. 可在【帮助中心】-积分规则查看详细说明</li>
                  <li>7. 如有疑问，请联系严选在线客服</li>
                </ul>
              </div>
            </div>
          </div>
        </van-popup>
      </div>
    </div>

    <div>
      <div class="pleaseChoose">
        <van-cell v-if="name" is-link @click="showChooseProup" :title="`已选择：${name}`"></van-cell>
        <van-cell v-else is-link @click="showChooseProup" title="请选择规格数量"></van-cell>
        <van-popup
          :close-on-click-overlay="false"
          v-model:show="showChoose"
          closeable
          @close="beforeClose"
          position="bottom"
          :style="{ height: '75%' }"
          :overlay-style="{ backgroundColor: ' rgba(0,0,0,.4)' }"
        >
          <div class="navInfo">
            <div class="leftImage">
              <img style="height: 99px; width: 98px" :src="skuInfo?.skuDefaultImg" alt="" />
            </div>
            <div class="rightInfo">
              <van-tag class="specialoffer" type="warning">特价</van-tag>
              <div class="price">
                <span>价格：¥{{ skuInfo?.price }}</span>
              </div>
              <div v-if="name" class="selected">已选择：{{ name }}</div>
              <div v-else class="selected">请选择规格数量</div>
            </div>
          </div>
          <div class="main">
            <!-- 选择商品规格 -->
            <div class="mainItem" v-for="(spu1, index) in spuSaleAttrData" :key="spu1.spuId">
              <div class="color">{{ spu1.saleAttrName }}</div>
              <!-- 商品规格属性 -->
              <div class="colorCate" v-for="(spu2, index) in spu1.spuSaleAttrValueList" :key="spu2.id">
                <div
                  class="tab"
                  :class="{ active: spu2.isChecked === '1' }"
                  @click="changeTab(spu1.spuSaleAttrValueList, spu2.id, spu2, index)"
                >
                  {{ spu2.saleAttrValueName }}
                </div>
              </div>
            </div>

            <div class="mainItem">
              <div class="color">数量</div>
              <div class="addOrSub">
                <div class="sub" @click="count('sub')">-</div>
                <label size="5" class="num">
                  <input class="ipt" @change="changeIpt($event)" type="text" placeholder="" v-model="goodsNum" />
                </label>
                <div class="add" @click="count('add')">+</div>
              </div>
            </div>
          </div>
        </van-popup>
      </div>
      <div class="city">
        <!-- v-model="value"  -->
        <van-field is-link readonly label="配送" placeholder="请选择配地址" @click="showPicker = true" />
        <van-popup :overlay-style="{ backgroundColor: ' rgba(0,0,0,.4)' }" v-model:show="showPicker" position="bottom">
          <!-- @confirm="onConfirm" -->
          <van-picker :style="{ height: '60%' }" :columns="columns" @cancel="showPicker = false" />
        </van-popup>
      </div>
      <div class="serve">
        <!-- v-model="value"  -->
        <van-field is-link readonly label="服务" placeholder="" @click="showPicker = true" />
        <van-popup :overlay-style="{ backgroundColor: ' rgba(0,0,0,.4)' }" v-model:show="showPicker" position="bottom">
          <!-- @confirm="onConfirm" -->
          <van-picker :style="{ height: '60%' }" :columns="columns" @cancel="showPicker = false" />
        </van-popup>
      </div>
    </div>

    <van-swipe class="swiper" :show-indicators="false" :autoplay="3000" :loop="false">
      <van-swipe-item class="swiperI">
        <img
          class="itemImg"
          src="https://yanxuan.nosdn.127.net/f4dfe061fd07172ba729071f221b870d.jpg?quality=75&type=webp&imageView&thumbnail=750x0"
          alt=""
        />
      </van-swipe-item>
      <van-swipe-item class="swiperI">
        <img
          class="itemImg"
          src="https://yanxuan.nosdn.127.net/b07067ed86ad8dffa08cc30fc2137e31.jpg?quality=75&type=webp&imageView&thumbnail=750x0"
          alt=""
        />
      </van-swipe-item>
    </van-swipe>

    <!-- tabbr -->
    <van-tabbar v-model="active" :safe-area-inset-bottom="true">
      <van-tabbar-item badge="1" class="item1">
        <template #icon="props">
          <van-icon name="service-o" />
        </template>
      </van-tabbar-item>
      <van-tabbar-item @click="debounceBuyCart" class="item">立即购买</van-tabbar-item>
      <van-tabbar-item @click="deAddCart" class="item">加入购物车 </van-tabbar-item>
    </van-tabbar>
  </div>
</template>
<script lang="ts">
import { defineComponent } from 'vue'
export default defineComponent({
  name: 'Detail'
})
</script>
<script lang="ts" setup>
import { onMounted, ref, computed } from 'vue'
import detailApi from '@/api/detail'
import type { skuImageData, skuInfo, spuSaleAttrData, spuSaleAttrValueData } from '@/api/detail'
import { useAddCartStore } from '@/stores/addcart'
import { showToast } from 'vant'
import { useRoute, useRouter } from 'vue-router'
import _ from 'lodash'

// 弹出层 状态
const showProup1 = ref(false)
const showProup2 = ref(false)
const showProup3 = ref(false)
const handleClick = (num: number) => {
  if (num === 1) showProup1.value = true
  else if (num === 2) showProup2.value = true
  else showProup3.value = true
}

// 接收规格的状态
const showChoose = ref(false)
const showChooseProup = () => {
  showChoose.value = true
}
const times = ref(0)
// 用来存放颜色尺寸等规格的属性值名字的数组
const newAttr = <any>ref([])
const showAddCart = () => {
  times.value++
  showChoose.value = true

  spuSaleAttrData.value.forEach((attr1: spuSaleAttrData) => {
    const spu = attr1.spuSaleAttrValueList.find((attr2: spuSaleAttrValueData) => attr2.isChecked === '1')
    newAttr.value.push(`${spu?.saleAttrName}：${spu?.saleAttrValueName}`)
  })

  // const goodsInfo = { skuName, skuDefaultImg, price, goodsNum, newAttr }

  // if (newAttr.value && newAttr.value.length > 1) {
  //   cartStore.addGoodsCart(id.value, goodsNum.value)
  //   showToast({ message: '加入成功', position: 'top' })
  // } else {
  //   showToast({ message: '请选择属性', position: 'top' })
  // }
  if (times.value === 2) {
    cartStore.addGoodsCart(id.value, goodsNum.value)
    showToast({ message: '加入成功', position: 'top' })
  } else {
    showToast({ message: '请选择属性', position: 'top' })
  }
}
// 防抖加入购物车
const deAddCart = _.debounce(showAddCart, 1000)

// 立即购买
const buyCart = () => {
  showChoose.value = true
  // 跳转到支付
  // router.push()
}

// 防抖
const debounceBuyCart = _.debounce(buyCart, 500)

// 规格规格属性关闭前的回调
const beforeClose = () => {
  newAttr.value = []
  times.value = 0
}

// 城市死数据
const columns = [
  { text: '杭州', value: 'Hangzhou' },
  { text: '宁波', value: 'Ningbo' },
  { text: '温州', value: 'Wenzhou' },
  { text: '绍兴', value: 'Shaoxing' },
  { text: '湖州', value: 'Huzhou' }
]
const result = ref('')
const showPicker = ref(false)

// tabBar
const active = ref(0)
const icon = {
  active: 'https://fastly.jsdelivr.net/npm/@vant/assets/user-active.png',
  inactive: 'https://fastly.jsdelivr.net/npm/@vant/assets/user-inactive.png'
}

// 点击高亮切换商品规格属性
const name = ref('')
const changeTab = (spuList: any, id: number, spu2: any, index: number) => {
  if (spu2.isChecked === '1') {
    spu2.isChecked = '0'
    name.value = ''
  } else if (spu2.isChecked === '0') {
    // spu2.isChecked = '1'
    spuList.forEach((item: any) => {
      if (item.id === id) {
        item.isChecked = '1'
      } else {
        item.isChecked = '0'
      }
      name.value = spu2.saleAttrValueName
    })
  }
}

// 生成随机id
const id = ref(Math.floor(Math.random() * 30))

// 获取商品商品详情请求
const price = ref<number>(0)
const skuImageList = ref<skuImageData[]>([])
const skuInfo = ref<skuInfo>()
const spuSaleAttrData = ref<spuSaleAttrData[]>([])
const skuDefaultImg = ref('')
const getDetail = async (skuId: number) => {
  // skuId=id.value
  const res = await detailApi.reqGoodInfo(skuId)
  id.value = res.data.skuInfo.spuId
  skuImageList.value = res.data.skuInfo.skuImageList
  price.value = res.data.price
  skuInfo.value = res.data.skuInfo
  spuSaleAttrData.value = res.data.spuSaleAttrList
  skuDefaultImg.value = res.data.skuInfo.skuDefaultImg
}

//  spuSaleAttrData.value.map((item:any) => {
//   return item.spuSaleAttrValueList.map((item:any) => {
//     return item.isChecked = '0'
//   })
// })
// 计算出skuName
const skuName = computed(() => {
  return skuInfo.value?.skuName
})

// 添加购物车
const goodsNum = ref(1) // 保存商品的购买数量
const cartStore = useAddCartStore()

// 点击加减
const count = (val: string) => {
  if (val === 'add') {
    //
    if (goodsNum.value === 200) return showToast({ message: '单次限买数量是99', position: 'top' })
    // ;('')
    goodsNum.value += Number(1) * 1
  } else if (val === 'sub') {
    if (goodsNum.value === 1) return showToast({ message: '最小的购买数量是0', position: 'top' })
    goodsNum.value -= 1 * 1
  }
}
// input用户输入的商品数量
const changeIpt = (e: any) => {
  const value = e.target.value
  const reg = /^([1-9]|[1-9]\d|1\d{2}|99)$/
  // 验证用户输入的值是否合法
  const res = reg.test(value)
  if (res) {
    // 用户输入的合法值
    goodsNum.value = value * 1
    // 大于99
  } else if (value > 99) {
    goodsNum.value = e.target.value = 200
  } else if (value < 1) {
    goodsNum.value = e.target.value = 1
  } else {
    goodsNum.value = e.target.value = 1
  }
}

onMounted(() => {
  getDetail(id.value)
})
</script>

<style lang="less" scoped>
.detail {
  height: 100%;
  .header {
    border-top: 1px solid #ddd;
    .headerSwiper {
      width: 100%;
      .swiperItem {
        height: 375px;
        width: 375px;
        .itemImg {
          height: 375px;
          width: 375px;
        }
      }
    }
  }
  .detailPrice {
    width: 100%;
    height: 74px;
    background-color: rgb(250, 30, 50);
    display: flex;
    color: white;
    .priceLeft {
      width: 285px;
      display: flex;
      flex-direction: column;
      justify-content: space-around;
      padding: 0 10px;
      .leftTop {
        font-size: 12px;
        margin-top: 5px;
      }
      .leftBottom {
        font-size: 12px;
        display: flex;
        // flex-direction: row;
        .bottomY {
          display: flex;
          align-items: center;
        }
        .Bottomprice {
          font-size: 42px;
          font-weight: 600;
          display: flex;
          align-items: center;
        }
        .priceToHand {
          display: inline-block;
          width: 80px;
          height: 24px;
          border-radius: 20px;
          line-height: 24px;
          text-align: center;
          background-color: #fff;
          color: rgb(250, 30, 50);
          margin-left: 5px;
          font-size: 16px;
          font-weight: 600;
          .hand {
            font-size: 12px;
          }
        }
      }
    }
    .priceRight {
      display: flex;
      align-items: center;
      .rightImg {
        width: 75px;
        height: 40px;
      }
    }
  }

  .baseInfo {
    height: 180px;
    // background-color: green;
    padding: 10px 0 0 0;
    .infoMain {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 0 10px;
      .mainLeft {
        .name {
          width: 130px;
          font-size: 18px;
          font-weight: 600;
          color: #333333;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
        .brandInfo {
          display: flex;
          margin: 10px 10px;
          .brand {
            display: flex;
            align-items: center;
            .proLogo {
              width: 32px;
              height: 16px;
              background: url(https://yanxuan.nosdn.127.net/6366944e4ac00118969787dedf9520e7.png) no-repeat;
              background-size: 100% 100%;
            }
            .brandLogo {
              width: 14px;
              height: 14px;
              margin: 0 5px;
              border-radius: 50%;
            }
            .title {
              font-size: 14px;
              color: #7f7f7f;
            }
          }
        }
        .desc {
          font-size: 12px;
          color: #333333;
        }
      }
      .mainRight {
        display: flex;
        align-items: center;
        position: relative;
        .rate {
          .percentage {
            font-size: 16px;
            color: #dd1a21;
            font-weight: 700;
          }
          .applauseRate {
            font-size: 12px;
            color: #333333;
          }
        }

        .rightClick {
          font-size: 18px;
          color: #7f7f7f;
          position: absolute;
          top: 8px;
          left: 41px;
        }
      }
    }
    .recmBanner {
      margin: 10px;
      height: 74px;
      background: #fafafa;
      border: 1px solid #e6e6e6;
      position: relative;
      .angleTop {
        position: absolute;
        .angleContent {
          width: 0;
          height: 0;
          border: 9px solid transparent;
          border-bottom: 9px solid #fafafa;
          position: absolute;
          left: 26px;
          top: -18px;
        }
      }
      .ulli {
        font-size: 12px;
        display: flex;
        flex-direction: column;
        padding: 5px 10px;
        justify-content: space-between;
        letter-spacing: 1px;
        .lili {
          color: #333;
          margin: 2px 0;
          .key {
            display: inline-block;
            width: 12px;
            height: 12px;
            border: 1px solid #dd1a21;
            border-radius: 50%;
            text-align: center;
            line-height: 12px;
            font-size: 12px;
            color: #dd1a21;
            font-family: PingFang SC;
            font-weight: 700;
            margin-right: 5px;
            vertical-align: middle;
          }
          .recommendReason {
            width: 300px;
            display: inline-block;
            height: 12px;
            line-height: 12px;
            vertical-align: middle;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }
        }
      }
    }
  }
  .welfareCard {
    height: 100px;
    background-color: #f4f4f4;
    display: flex;
    align-items: center;
    .cardImg {
      width: 100%;
      height: 70px;
    }
  }
  .proupInfo {
    .proupP {
      padding: 10px;
      box-sizing: border-box;
      .van-cell {
        align-items: center;
      }
      .nav {
        .picker-z {
          height: 315px;
          padding: 10px;
          box-sizing: border-box;
          .ruleTitle {
            font-size: 14px;
            margin-top: 15px;
            margin-bottom: 10px;
            &::before {
              content: ' ';
              background: #dd1a21;
              height: 5px;
              width: 5px;
              border-radius: 50%;
              display: inline-block;
            }
          }
          .ruleContent {
            font-size: 14px;
            color: #7f7f7f;
          }
        }
      }
    }
  }
  .pleaseChoose {
    // height:50px;
    padding: 10px 0;
    background-color: #f4f4f4;
    margin-top: 10px;
    // .van-popup--bottom{
    //   bottom: 50px;
    // }
    .van-cell {
      height: 50px;
      line-height: 50px;
      align-items: center;
      padding: 0 10px;
    }
    .navInfo {
      height: 120px;
      display: flex;
      align-items: center;
      .leftImage {
        background-color: #f4f4f4;
        margin: 0 10px;
      }
      .rightInfo {
        width: 160px;
        .specialoffer {
          width: 32px;
          height: 17px;
          text-align: center;
          padding-left: 4.5px;
          box-sizing: border-box;
          border-radius: 3px;
        }
        .price {
          color: #dd1a21;
          font-size: 14px;
        }
        .selected {
          font-size: 14px;
          width: 150px;
        }
      }
    }
    .main {
      padding: 0 10px;
      height: 600px;
      .mainItem {
        margin-bottom: 10px;
        .color {
          font-size: 14px;
          margin-bottom: 10px;
        }
        .colorCate {
          display: flex;
          flex-direction: column;
          justify-content: space-between;
          .tab {
            width: 160px;
            height: 36px;
            line-height: 36px;
            text-align: center;
            border: 1px solid #7f7f7f;
            border-radius: 4px;
            font-size: 13px;
            margin-bottom: 10px;
            color: #333333;
            &.active {
              border: 1px solid red;
            }
          }
        }
        .addOrSub {
          height: 44px;
          display: flex;
          .sub {
            width: 45px;
            height: 31px;
            border: 1px solid black;
            box-sizing: border-box;
            border-right: 0;
            text-align: center;
            line-height: 31px;
          }
          .add {
            width: 45px;
            height: 31px;
            border: 1px solid black;
            box-sizing: border-box;
            // border-left: 0;
            text-align: center;
            line-height: 31px;
          }
          .num {
            // border: 1px solid red;
            border: 1px solid black;
            height: 31px;
            width: 66px;
            font-size: 14;
            box-sizing: border-box;
            position: relative;
            :deep(.ipt) {
              width: 66px;
              border: 0;
              padding-left: 25px;
              box-sizing: border-box;
              font-size: 16px;
              position: absolute;
              top: 0;
              left: 0;
              right: 0;
              bottom: 0;
              border-right: 1px solid black;
            }
          }
        }
      }
    }
  }
  .city {
    height: 50px;
    padding: 0 10px;
    box-sizing: border-box;
    .van-cell {
      height: 50px;
      line-height: 50px;
      align-items: center;
    }
  }
  .serve {
    height: 50px;
    padding: 0 10px;
    box-sizing: border-box;
    .van-cell {
      height: 50px;
      line-height: 50px;
      align-items: center;
    }
  }
  .swiper {
    height: 200px;
    padding: 10px 0 0 0;
    background-color: #f4f4f4;
    .swiperI {
      .itemImg {
        width: 100%;
        height: 100px;
      }
    }
  }
  // tabbar
  .van-tabbar--fixed {
    z-index: 10000;
  }
  .van-tabbar {
    .item1 {
      height: 52;
      box-sizing: border-box;
      border: 1px solid #ccc;
      border-right: 0;
    }
    .item {
      font-size: 14px;
      height: 52;
      border: 1px solid #ccc;
      box-sizing: border-box;
      &:last-child {
        background-color: #dd1a21;
        color: white;
        border: 0;
      }
    }
  }
}
</style>
